﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using System.Xml;
namespace BP.OA
{
    public class Main
    {
        /// <summary>
        /// 获取当前时间 格式：2014-07-01 12：33：33
        /// </summary>
        public static DateTime CurDateTime
        {
            get
            {
                return Convert.ToDateTime(String.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now));
            }
        }
        /// <summary>
        /// 获取当前时间 格式：2014-07-01 12：33：33
        /// </summary>
        public static string CurDateTimeStr
        {
            get
            {
                return String.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
            }
        }
        /// <summary>
        /// 转换日期格式：2014-07-01 12：33：33
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static string TransDateTime(string dateTime)
        {
            try
            {
                DateTime dt = DateTime.Parse(dateTime);
                return dt.ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch (Exception ex) { 
            }
            return dateTime;
        }
        /// <summary>
        /// 转换日期格式：2014-07-01
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static string TransDateTimeShort(string dateTime)
        {
            try
            {
                DateTime dt = DateTime.Parse(dateTime);
                return dt.ToString("yyyy-MM-dd");
            }
            catch (Exception ex)
            {
            }
            return dateTime;
        }
        /// <summary>
        /// 转换日期格式：2014年07月01日
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static string TransDateTimeShortQ(string dateTime)
        {
            try
            {
                DateTime dt = DateTime.Parse(dateTime);
                return dt.ToString("yyyy年M月d日");
            }
            catch (Exception ex)
            {
            }
            return dateTime;
        }
        
        /// <summary>
        /// 转换日期格式：2014-07-01 12：33：33
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static string TransDateTime(DateTime dateTime)
        {
            try
            {
                return dateTime.ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch (Exception ex)
            {
            }
            return dateTime.ToString();
        }
        /// <summary>
        /// 转换格式，格式：yyyy年MM月dd日
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static string TransDate_CN(string dateTime)
        {
            try
            {
                DateTime dt = DateTime.Parse(dateTime);
                return dt.ToString(BP.DA.DataType.SysDataFormatCN);
            }
            catch (Exception ex)
            {
            }
            return dateTime;
        }
        /// <summary>
        /// 固定资产求和(未找到相应方法,重新写的)
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static string getSum(string sql)
        {
            DataTable dt = BP.DA.DBAccess.RunSQLReturnTable(sql);
            int getSum=0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                getSum += (System.Int32.Parse(dt.Rows[i]["Money"].ToString()));
            }
            return getSum.ToString();
        }

        //在线状态
        private static int LimitSeconds = 30;
        private static DataTable _OnLineUsers = null;
        public static DataTable OnLineUsers { get { return _OnLineUsers; } }
        public static void CheckUser(string userNo)
        {
            if (_OnLineUsers == null)
            {
                _OnLineUsers = new DataTable();
                _OnLineUsers.Columns.Add("UserNo");
                _OnLineUsers.Columns.Add("LoginTime");
                _OnLineUsers.Columns.Add("LastUpdatedTime");
            }
            else
            {
                //超过30秒自动离线
                for (int i = _OnLineUsers.Rows.Count - 1; i >= 0; i--)
                {
                    DataRow dr = _OnLineUsers.Rows[i];
                    DateTime lastUpdate = Convert.ToDateTime(dr["LastUpdatedTime"]);
                    if ((DateTime.Now - lastUpdate).TotalSeconds > LimitSeconds)
                    {
                        lock (_OnLineUsers)
                        {
                            _OnLineUsers.Rows.Remove(dr);
                        }
                    }
                }
            }
            //个人在线状态
            DataRow[] drs = _OnLineUsers.Select(String.Format("UserNo='{0}'", userNo));
            if (drs.Length == 0)
            {
                lock (_OnLineUsers)
                {
                    _OnLineUsers.Rows.Add(userNo, DateTime.Now, DateTime.Now);
                }
            }
            else
            {
                DataRow dr = drs[0];
                dr["LastUpdatedTime"] = DateTime.Now;
            }
        }
        public static int OnlineCount
        {
            get
            {
                if (_OnLineUsers == null)
                    return 0;
                else
                    return _OnLineUsers.Rows.Count;
            }
        }
        //获取appSetting
        public static string GetConfigItem(string key)
        {
            if (System.Configuration.ConfigurationManager.AppSettings[key] == null)
                return null;
            else
                return System.Configuration.ConfigurationManager.AppSettings[key].ToString();
        }
        //修改appSetting
        public static void SetConfigItem(string key, object value)
        {
            XmlDocument doc = new XmlDocument();
            //获得配置文件的全路径
            doc.Load(HttpContext.Current.Server.MapPath("/") + "/Web.config");
            //找出名称为“add”的所有元素            
            XmlNodeList nodes = doc.GetElementsByTagName("appSettings")[0].ChildNodes;
            int i = 0;
            for (i = 0; i < nodes.Count; i++)
            {
                //获得将当前元素的key属性
                if (nodes[i].Attributes == null) continue;
                if (nodes[i].Attributes["key"] == null) continue;
                XmlAttribute att = nodes[i].Attributes["key"];
                //根据元素的第一个属性来判断当前的元素是不是目标元素
                if (att.Value == key)
                {
                    //对目标元素中的第二个属性赋值
                    att = nodes[i].Attributes["value"];
                    att.Value = Convert.ToString(value);
                    break;
                }
            }
            if (i >= nodes.Count)
            {
                throw new ApplicationException(String.Format("没有发现AppSetting({0})项", key));
            }
            doc.Save(HttpContext.Current.Server.MapPath("/web.config"));
        }
        /// <summary>
        /// 判断在输入时间在某个时间段显示某个图标。
        ///    目前用来“最新图标”。
        /// </summary>
        /// <param name="eval_DateTime"></param>
        /// <param name="title"></param>
        /// <param name="maxHours"></param>
        /// <param name="imgUrl"></param>
        /// <returns></returns>
        public static string GetTimeImg(object eval_DateTime, int maxHours, String title, String imgUrl, int imgWidth, int imgHeight)
        {
            DateTime dt = Convert.ToDateTime(eval_DateTime);
            string imgStyle = imgWidth == 0 || imgHeight == 0 ? String.Empty : "Style = 'width:{2}px;height:{3}px;'";
            return (DateTime.Now - dt).TotalHours > maxHours ? String.Empty
                : String.Format("<img src='{0}' " + imgStyle + " alt='{1}' />", imgUrl, imgWidth, imgHeight, title);
        }
        /// <summary>
        /// 得到时间与现在的时间差字符串
        /// 例如：GetTimeEslapseStr(myDate,"还有{0}{1}","{0}{1}前")
        /// </summary>
        /// <param name="dt">时间</param>
        /// <param name="comingFormat">还不到的时间格式：还有{0}{1}</param>
        /// <param name="pastFormat">已过的时间格式：{0}{1}前</param>
        /// <returns></returns>
        /// 
        public static string GetTimeEslapseStr(DateTime dt, string comingFormat, string pastFormat)
        {
            return GetTimeEslapseStr(dt, comingFormat, pastFormat, false);
        }
        public static string GetTimeEslapseStr(DateTime dt, string comingFormat, string pastFormat, bool onlyDay)
        {
            if (dt == null)
                return "";
            if (String.IsNullOrEmpty(comingFormat)) comingFormat = "还有{0}{1}";
            if (String.IsNullOrEmpty(pastFormat)) pastFormat = "{0}{1}前";
            TimeSpan ts = DateTime.Now - dt;
            if (ts.Days != 0)
            {
                if (ts.Days > 0)
                    return String.Format(pastFormat, ts.Days, "天");
                else
                    return String.Format(comingFormat, -ts.Days, "天");
            }
            else if (ts.Hours != 0 && !onlyDay)
            {
                if (ts.Hours > 0)
                    return String.Format(pastFormat, ts.Hours, "小时");
                else
                    return String.Format(comingFormat, -ts.Hours, "小时");
            }
            else if (ts.Minutes != 0 && !onlyDay)
            {
                if (ts.Minutes > 0)
                    return String.Format(pastFormat, ts.Minutes, "分钟");
                else
                    return String.Format(comingFormat, -ts.Minutes, "分钟");
            }
            else if (!onlyDay)
            {
                if (ts.Seconds > 0)
                    return String.Format(pastFormat, ts.Seconds, "秒");
                else
                    return String.Format(comingFormat, -ts.Seconds, "秒");
            }
            else
            {
                return "今天";
            }
        }
        /// <summary>
        /// 从数据库中获取分页记录集
        /// </summary>
        /// <param name="sql">Sql语句,(1-不能为Top,2-不能有Order By条件串)</param>
        /// <param name="top">前N条，大于0时起作用</param>
        /// <param name="orderBy">排序字符串Order by FieldName</param>
        /// <param name="pageSize">每页N条</param>
        /// <param name="pageIndex">第N页</param>
        /// <returns></returns>
        public static DataTable GetPagedRows(string sql, int top, string orderBy, int pageSize, int pageIndex)
        {
            string sSql = String.Format("exec SYST_pGetPageRows '{0}',{1},'{2}',{3},{4}", sql.Replace("'", "''"), top, orderBy, pageSize, pageIndex);
            if (BP.Sys.SystemConfig.AppCenterDBType == BP.DA.DBType.MySQL)
            {
                sSql = String.Format("call SYST_pGetPageRows('{0}',{1},'{2}',{3},{4})", sql.Replace("'", "''"), top, orderBy, pageSize, pageIndex);
            }
            return BP.DA.DBAccess.RunSQLReturnTable(sSql);
        }
        /// <summary>
        /// 获取数据的记录数
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int GetPagedRowsCount(string sql)
        {
            sql = "Select Count(*) from (" + sql + ") as ABCXYZ_CCFLOW";
            return Convert.ToInt32(BP.DA.DBAccess.RunSQLReturnVal(sql));
        }
        /// <summary>
        /// 将数组转化为数据表，用来测试用！
        /// </summary>
        /// <param name="aData"></param>
        /// <param name="sSplitter"></param>
        /// <returns></returns>
        public static DataTable GetTestTable(string[] aData)
        {
            return GetTestTable(aData, ",");
        }
        /// <summary>
        /// 将数组转化为数据表，用来测试用！
        /// </summary>
        /// <param name="aData"></param>
        /// <param name="sSplitter"></param>
        /// <returns></returns>
        public static DataTable GetTestTable(string[] aData, string sSplitter)
        {
            int i;
            DataTable dt = new DataTable();
            string[] aHeader = aData[0].Split(new string[] { sSplitter }, StringSplitOptions.None);
            for (i = 0; i < aHeader.Length; i++)
            {
                dt.Columns.Add(aHeader[i]);
            }
            for (i = 1; i < aData.Length; i++)
            {
                string[] aHeader1 = aData[i].Split(new string[] { sSplitter }, StringSplitOptions.None);
                DataRow dr = dt.Rows.Add(aHeader1);
            }
            return dt;
        }
        /// <summary>
        /// 格式化行集。
        /// 如：GetValueListFromDataRowArray(drs变量，"[{0}-{1}-{2}]" , ";"  , "ID,Name,Phone")  = 
        ///       1-孙强-84932234;2-张世强-85071123;3-朱诚-13288374538
        /// </summary>
        /// <param name="drs">行集</param>
        /// <param name="format">格式化字符串</param>
        /// <param name="splitter">分隔符</param>
        /// <param name="columns">已知列</param>
        /// <returns></returns>
        public static string GetValueListFromDataRowArray(DataRow[] drs, String format, String splitter, String columns)
        {
            if (String.IsNullOrEmpty(format)) format = "{0}";
            StringBuilder sb = new StringBuilder();
            foreach (DataRow dr in drs)
            {
                if (sb.Length != 0) sb.Append(splitter);
                List<object> l_o = new List<object>();
                String[] arr_columns = columns.Split(new String[] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (String column in arr_columns)
                {
                    l_o.Add(dr[column]);
                }
                string f = format;
                //if (Convert.ToInt32(dr["Succeed"]) == 1)
                //    f = String.Format("<span style='text-decoration:none;'>{0}</span>", f);
                //else
                //    f = String.Format("<span style='text-decoration:none;color:#444;'>{0}</span>", f);
                sb.AppendFormat(f, l_o.ToArray());
            }
            return sb.ToString();
        }
        public static string ReadTextFile(string file)
        {
            System.IO.StreamReader read = new System.IO.StreamReader(file, System.Text.Encoding.UTF8); // 文件流.
            string doc = read.ReadToEnd();  //读取完毕。
            read.Close(); // 关闭。
            return doc;
        }
        public static bool SaveAsFile(string filePath, string doc)
        {
            System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath, false);
            sw.Write(doc);
            sw.Close();
            return true;
        }
        /// <summary>
        /// 获取参数化的字符串，如：GetParameteredString("ID:@ID,Name:@Name",dr变量) = "ID:1,Name:王杨"
        /// </summary>
        /// <param name="stringInput"></param>
        /// <param name="dr"></param>
        /// <returns></returns>
        private string GetParameteredString(string stringInput, DataRow dr)
        {
            String regE = "@[a-zA-Z]([\\w-]*[a-zA-Z0-9])?"; //字母开始，字母+数字结尾，字母+数字+下划线+中划线中间
            //String regE = "@[\\w-]+";                              //字母+数字+下划线+中划线
            MatchCollection mc = Regex.Matches(stringInput, regE, RegexOptions.IgnoreCase);
            foreach (Match m in mc)
            {
                string v = m.Value;
                string f = m.Value.Substring(1);
                if (dr.Table.Columns.Contains(f))
                {
                    stringInput = stringInput.Replace(v, String.Format("{0}", dr[f]));
                }
            }
            return stringInput;
        }
        public static void DeleteFiles_By_StrList(string files)
        {
            if (!String.IsNullOrEmpty(files))
            {
                string[] arr_files = files.Split(new String[] { ",", ";", "|" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (String file in arr_files)
                {
                    try
                    {
                        System.IO.File.Delete(HttpContext.Current.Server.MapPath(file));
                    }
                    catch
                    {
                        ;
                    }
                }
            }
        }
        public static void DeleteFiles_By_DT(DataTable dt)
        {
            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        string files = String.Format("{0}", dr[i]);
                        if (!String.IsNullOrEmpty(files))
                        {
                            DeleteFiles_By_StrList(files);
                        }
                    }
                }
            }
        }
        public static void DeleteFiles_By_Sql(string sql)
        {
            DataTable dt = BP.DA.DBAccess.RunSQLReturnTable(sql);
            if (dt != null)
            {
                DeleteFiles_By_DT(dt);
            }
        }
    }
}
